import { appName, appVersion, root } from '@src/assets/js/config'
import style from './index.module.less'
import { Form, Input, Button, Toast, Dialog } from 'antd-mobile'
import { mobileLoginRequest, sendSMSRequest, usernameLoginRequest } from './ajax'
import { awaitWrap, compress, decompress, getUrlPre } from '@src/assets/js/tool'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import { setSendTime, setToken, setUserInfo } from '@src/redux/reducers/basic'
import { useEffect, useState } from 'react'
import classNames from 'classnames'
import { EyeInvisibleOutline, EyeOutline, CheckOutline } from 'antd-mobile-icons'
// import uuid from 'uuid'
// import { setList } from '@redux/reducers/pages'
import logo from '@imgs/logo.png'
import { useHistory } from 'react-router-dom'
const p = getUrlPre()
const { Item, useForm } = Form
let timer

async function loginByMobile (mobile, verification, callback) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(mobileLoginRequest(compress(mobile), verification))
  if (e === null && d !== null) {
    Toast.clear()
    callback(d)
  }
}

async function loginByUsername (mobile, verification, callback) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(usernameLoginRequest(mobile, verification))
  if (e === null && d !== null) {
    Toast.clear()
    callback(d)
  }
}


async function sendHandle (mobile, callback) {
  if (!mobile) {
    Toast.show({ content: '手机号不能为空' })
    return undefined
  }
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    Toast.show({ content: '手机号格式不正确' })
    return undefined
  }
  Toast.show({ content: '发送中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(sendSMSRequest(compress(mobile)))
  if (e === null) {
    Toast.clear()
    callback()
  }
}

function loop (sendTime, setSecond) {
  const n = 60 - Math.floor((Date.now() - sendTime) / 1000)
  if (n >= 0) {
    setSecond(n)
    timer = setTimeout(() => {
      loop(sendTime, setSecond)
    }, 1000)
  }
}

function getMobileLoginable (m, v) {
  return m && /^1[3-9]\d{9}$/.test(m) && v && /^\d{4}$/.test(v)
}

function afterLogin (h, data, dispatch) {
  // data.userInfo.is_auth = 0
  if (data.userInfo.is_auth !== 1) {
    h.push(`${root}/gate/verification`)
    // dispatch(setList([{ element: 'verification', title: '身份认证', id: uuid() }]))

  } else {
    h.replace(`${root}/gate/home`)
    // dispatch(setList([{ element: 'home', title: '首页', id: uuid() }]))
  }
  const u = data.userInfo
  if (typeof u.mobile === 'string' && u.mobile.length > 0) {
    u.mobile = decompress(u.mobile)
  }
  Dialog.show({
    content: <span style={{ color: 'red' }}>此系统为非涉密系统，严禁上传涉密信息。</span>,
    actions: [{ key: '0', text: '确定' }],
    closeOnAction: true
  })
  dispatch(setToken(data.token))
  dispatch(setUserInfo(u))
}

function MobileLogin ({ toggle, agree, setAgree }) {
  const dispatch = useAppDispatch()
  const [formRef] = useForm()
  const [second, setSecond] = useState(0)
  const sendTime = useAppSelector(state => state.basic.sendTime)
  const h = useHistory()
  useEffect(() => {
    loop(sendTime, setSecond)
    return () => {
      timer && clearTimeout(timer)
    }
  }, [sendTime])
  return (
    <Form layout='horizontal' form={formRef} onFinish={d => loginByMobile(d.mobile, d.verification, d => afterLogin(h, d, dispatch))}>
      <Item label='手机号' name='mobile' required={false} rules={[
        { required: true, message: '手机号不能为空' },
        { validator(rule, value) {
          if (value && !/^1[3-9]\d{9}$/.test(value)) {
            return Promise.reject(new Error('手机号格式不正确'))
          }
          return Promise.resolve()
        }, }
      ]}>
        <Input placeholder='请输入' maxLength={11} clearable />
      </Item>
      <Item
        label='验证码'
        name='verification'
        required={false}
        rules={[
          { required: true, message: '验证码不能为空' },
          { validator(rule, value) {
            if (value && !/^\d{4}$/.test(value)) {
              return Promise.reject(new Error('验证码格式不正确'))
            }
            return Promise.resolve()
          }, }
        ]}
        extra={
          (
            second === 0 ? (
              <div className={style.send} onClick={() => {
                const mobile = formRef.getFieldValue('mobile')
                sendHandle(mobile, () => { dispatch(setSendTime(Date.now())) })
              }}>
                <a>获取验证码</a>
              </div>
            ) : (
              <div className={classNames(style.send, style.disabled)}><span>{second} s</span></div>
            )
          )
        }
      >
        <Input placeholder='请输入验证码' maxLength={4} clearable />
      </Item>
      <div className={style['toggle-type-line']}>
        <span onClick={toggle}>用帐号密码登录</span>
        <span onClick={() => { h.push(`${root}/gate/registry`) }}>去注册</span>
      </div>
      <div className={style['agree-line']} onClick={() => setAgree(!agree)}>
        <div className={style.checkbox}>
          {agree && <CheckOutline />}
        </div>
        <div className={style['agree-text']}>
          <span>我同意黑黑龙江省仲裁网办使用我所提交的手机号用于快捷注册/登录。查看</span>
          <a onClick={(e) => { e.stopPropagation() }}>《用户服务协议》</a>
          <span>及</span>
          <a onClick={(e) => { e.stopPropagation() }}>《隐私政策》</a>
        </div>
      </div>
      <div className={style['btn-line']}>
        <Item noStyle shouldUpdate={(pre, cur) => pre.mobile !== cur.mobile || pre.verification !== cur.verification}>
          {
            ({ getFieldValue }) => {
              const m = getFieldValue('mobile')
              const v = getFieldValue('verification')
              const able = getMobileLoginable(m, v)
              return (
                <Button block color='primary' type='submit' size='large' disabled={!able || !agree}>登录</Button>
              )
            }
          }
        </Item>
      </div>
    </Form>
  )
}

function UsernameLogin ({ toggle, agree, setAgree }) {
  const dispatch = useAppDispatch()
  const [visible, setVisible] = useState(false)
  const [formRef] = useForm()
  const h = useHistory()
  return (
    <Form layout='horizontal' form={formRef} onFinish={d => loginByUsername(d.username, d.password, d => afterLogin(h, d, dispatch))}>
      <Item label='账号' name='username' required={false} rules={[
        { required: true, message: '账号不能为空' }
      ]}>
        <Input placeholder='请输入' maxLength={11} clearable />
      </Item>
      <Item label='密码' name='password'
        rule={[
          { required: true, message: '密码不能为空' }
        ]}
        extra={
          <div className={style.eye}>
            {!visible ? (
              <EyeInvisibleOutline onClick={() => setVisible(true)} />
            ) : (
              <EyeOutline onClick={() => setVisible(false)} />
            )}
          </div>
        }
      >
        <Input placeholder='请输入密码' clearable type={visible ? 'text' : 'password'} />
      </Item>
      <div className={style['toggle-type-line']}>
        <span onClick={toggle}>用手机号登录</span>
        <span onClick={() => { h.push(`${root}/gate/registry`) }}>去注册</span>
      </div>
      <div className={style['agree-line']} onClick={() => setAgree(!agree)}>
        <div className={style.checkbox}>
          {agree && <CheckOutline />}
        </div>
        <div className={style['agree-text']}>
          <span>我同意黑龙江省仲裁网办使用我所提交的手机号用于快捷注册/登录。查看</span>
          <a onClick={(e) => { e.stopPropagation() }}>《用户服务协议》</a>
          <span>及</span>
          <a onClick={(e) => { e.stopPropagation() }}>《隐私政策》</a>
        </div>
      </div>
      <div className={style['btn-line']}>
        <Item noStyle shouldUpdate={(pre, cur) => pre.username !== cur.username || pre.password !== cur.password}>
          {
            ({ getFieldValue }) => {
              const m = getFieldValue('username')
              const v = getFieldValue('password')
              return (
                <Button block color='primary' type='submit' size='large' disabled={!m || !v || !agree}>登录</Button>
              )
            }
          }
        </Item>
      </div>
    </Form>
  )
}

function Main () {
  const [isMobile, setIsMobile] = useState(true)
  const [agree, setAgree] = useState(false)
  const h = useHistory()
  useEffect(() => {
    if (p !== 'gate') {
      location.href = `${location.origin}${root}/gate/login`
    }
  }, [])
  return (
    <div className={style.container}>
      <div className={style['app-name']} onClick={() => { h.push(`${root}/gate/home`) }}>
        <img src={logo} />
        <span>{appName}</span>
      </div>
      <div className={style['app-name-sub']}>黑龙江省仲裁网办 - 当事人</div>
      <div className={style['login-type-line']}>
        {
          isMobile ? (
            <span>手机号登录</span>
          ) : (
            <span>账号密码登录</span>
          )
        }
      </div>
      {
        isMobile ? (
          <MobileLogin toggle={() => setIsMobile(false)} agree={agree} setAgree={setAgree} />
        ) : (
          <UsernameLogin toggle={() => setIsMobile(true)} agree={agree} setAgree={setAgree} />
        )
      }
      <div className={style.version}>v {appVersion}</div>
    </div>
  )
}

export default Main
